package com.lyw.springCloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.lyw.springCloud.entities.Payment;
import com.lyw.springCloud.handler.ExceptionUtil;
import com.lyw.springCloud.result.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Auther liyawei
 * @Date 2022/5/18 17:17
 */
@Slf4j
@RestController
public class RateLimitController {

    @GetMapping("/byResource")
    @SentinelResource(value = "byResourceQWER", blockHandler = "handlerException")
    public CommonResult byResource(){

        return new CommonResult(200, "按资源名称限流测试OK", new Payment(2020L, "serial001"));
    }

    @GetMapping("/byUrl/url")
    @SentinelResource
    public CommonResult byUrl(){

        return new CommonResult(200, "按资源名称限流测试OK", new Payment(2020L, "serial001"));
    }

    public CommonResult handlerException(BlockException e){
        return new CommonResult(404, e.getClass().getCanonicalName()+"\t 服务不可用");
    }

    /**
     * 假如限流规则满足，由 blockHandlerClass 的类中的 blockHandler 的方法进行兜底
     * @return
     */
    @GetMapping("/customerBlockHandler")
    @SentinelResource(blockHandlerClass = ExceptionUtil.class, blockHandler = "handleException1")
    public CommonResult customerBlockHandler(){

        return new CommonResult(200, "全局的客户自定义处理", new Payment(2020L, "serial003"));
    }
}
